const crypto = require('crypto')
const url = require('url')

exports.wechat = function (req, res) {
  const { query } = url.parse(req.url, true)
  const { signature } = query
  const { timestamp } = query
  const { nonce } = query
  const { echostr } = query
  if (check(timestamp, nonce, signature, 'bssfood')) {
    res.end(echostr)
  } else {
    res.end('It is not from weixin')
  }
}

function check(timestamp, nonce, signature, token) {
  let currSign; let tmp
  tmp = [token, timestamp, nonce].sort().join('')
  currSign = crypto.createHash('sha1').update(tmp).digest('hex')
  return (currSign === signature)
}
